
--[[
*********************************************************************************
** 
** Copyright 2021-2024 LuaOS
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
** 
*********************************************************************************
]]--

---------------------------------------------------------------------------------

local original = pairs;

---------------------------------------------------------------------------------

local function lt(a, b)
  if type(a) == "number" and type(b) == "number" then
    if a < b then return true
    else return false end
  end
  if tostring(a) < tostring(b) then 
    return true
  end
end

---------------------------------------------------------------------------------

local function gt(a, b)
  if type(a) == "number" and type(b) == "number" then
    if a > b then return true
    else return false end
  end
  if tostring(a) > tostring(b) then 
    return true
  end
end

---------------------------------------------------------------------------------

local function __pairs(t, f)
  if f == nil then
    return original(t);
  end
  local a = {}
  for k in original(t) do table.insert(a, k) end
  if type(f) == "string" then
    if f == "<" then
      f = lt
    elseif f == ">" then
      f = gt
    end
  end
  if type(f) ~= "function" then
    assert("invalid option");
  end
  table.sort(a, f)
  local i = 0         -- iterator variable
  local iter = function ()  -- iterator function
     i = i + 1
     if a[i] == nil then return nil
     else return a[i], t[a[i]]
     end
  end
  return iter
end

---------------------------------------------------------------------------------

return __pairs;

---------------------------------------------------------------------------------
